﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Foothill.IoC;
using Foothill.Model;
using Foothill.Service.AdService;
using Foothill.Service.Caching;
using Foothill.Web.Presenter;
using Foothill.Service.Session;
using Foothill.Service.SystemMessage;
using Foothill.Common;

namespace Foothill.Web
{
    public partial class PostForSaleCodeBehind : FoothillBasePage, IPostForSaleView
    {
        private PostForSalePresenter _presenter;
        private ISystemMessageService _systemMessageService; 

        protected void Page_Load(object sender, EventArgs e)
        {
            _systemMessageService = IocContainer.GetInstance<ISystemMessageService>();
            _presenter = IocContainer.GetInstance<PostForSalePresenter>();
            _presenter.View = this;

            if (!IsPostBack)
            {
                // initiate the page
                _presenter.InitPage();
                
                // populate the models for the selected make
                ddlMake.SelectedIndex = 0;
                _presenter.VehicleMakeSelected(Convert.ToInt32(ddlMake.SelectedValue));

                HideValidationLabels();
                SetupTipLabelText();
                rbtUsed.Checked = true;
                rbtAutomatic.Checked = true;   
            }
        }

        public void PopulateVehicleMake(IDictionary<int, string> dict)
        {
            PopulateDropDownList(ddlMake, dict);
        }

        public void PopulateVehicleModel(IDictionary<int, string> dict)
        {
            PopulateDropDownList(ddlModel, dict);
        }

        public void PopulateYearList(IDictionary<int, string> dict)
        {
            PopulateDropDownList(ddlYear, dict);
        }

        public void PopulateCityList(IDictionary<int, string> dict)
        {
            PopulateDropDownList(ddlCity, dict);
        }

        public void PopulateContactInformation(string contactName, string email, string phone)
        {
            txtEmail.Text = email;
            txtPhone.Text = phone;
            tbxContactName.Text = contactName;
        }

        protected void ddlMake_OnSelectedIndexChanged(Object sender, EventArgs e)
        {
            _presenter.VehicleMakeSelected(Convert.ToInt32( ddlMake.SelectedValue));
        }

        private void HideValidationLabels()
        {
            lblMileAgeValidation.Visible = false;
            lblPriceValidation.Visible = false;
            lblEmailValidation.Visible = false;
            lblModelValidation.Visible = false;
            lblDescriptionValidation.Visible = false;
        }

        private void SetupTipLabelText()
        {
            lblMileAgeTip.Text = _systemMessageService.GetSystemMessage(SystemMessageCategory.Web, SystemMessageCode.Mileage_Tip);
            lblPriceTip.Text = _systemMessageService.GetSystemMessage(SystemMessageCategory.Web, SystemMessageCode.Price_Tip);
        }
        
        protected void btnSubmit_Click( object sender, EventArgs e )
        {
            ForSaleAd newAd = PopulateNewAd();

            // submit to session
            _presenter.TrySubmitNewAd(newAd); 
        }

        private ForSaleAd PopulateNewAd()
        {
            ForSaleAd newAd = new ForSaleAd();

            ILocalCache localCache = IocContainer.GetInstance<ILocalCache>();

            newAd.ModelId = Convert.ToInt32(ddlModel.SelectedValue);
            newAd.ModelName = ddlModel.SelectedItem.Text;
            newAd.MakeId = Convert.ToInt32(ddlMake.SelectedItem.Value);
            newAd.MakeName = ddlMake.SelectedItem.Text;
            newAd.VehicleConditionId = rbtNew.Checked ? (int)VehicleCondition.New : (int)VehicleCondition.Used;
            newAd.YearMade = Convert.ToInt32(ddlYear.SelectedValue);
            newAd.YearMadeStr = ddlYear.SelectedItem.Text;
            newAd.MileAgeStr = Server.HtmlEncode(txtMileAge.Text.Trim());
            newAd.TransmissionTypeId = rbtAutomatic.Checked ? (int)TransmissionType.Automatic : (int)TransmissionType.Manual;
            newAd.TransmissionTypeName = localCache.GetStringValue(ApplicationDataNames.TransmissionType, newAd.TransmissionTypeId);
            newAd.PriceStr = Server.HtmlEncode(txtPrice.Text.Trim());

            newAd.Description = txtDescription.Text.Trim(); 

            newAd.ListingTypeId = rbtListingTypeOwner.Checked ? (int)ListingTypes.Owner : (int)ListingTypes.Dealer;
            newAd.CityId = Convert.ToInt32(ddlCity.SelectedValue);
            newAd.CityName = ddlCity.SelectedItem.Text;
            newAd.ContactPhone = Server.HtmlEncode(txtPhone.Text.Trim());
            newAd.ContactEmail = Server.HtmlEncode(txtEmail.Text.Trim());
            newAd.ContactName = Server.HtmlEncode(tbxContactName.Text.Trim());
            return newAd;
        }

        // for each input control failed in validation, display validation error message
        public void DisplayInvalidPageMessage(IDictionary<PostForSaleFields, string> dict)
        {
            Dictionary<PostForSaleFields, Label> mapping = new Dictionary<PostForSaleFields, Label>()
            {
                { PostForSaleFields.Price, lblPriceValidation },
                { PostForSaleFields.MileAge, lblMileAgeValidation },
                { PostForSaleFields.ContactEmail, lblEmailValidation },
                { PostForSaleFields.ModelId, lblModelValidation },
                { PostForSaleFields.Description, lblDescriptionValidation }
            };

            HideValidationLabels();

            foreach (KeyValuePair<PostForSaleFields, string> item in dict)
            {
                Label lbl = mapping[item.Key];
                lbl.Text = item.Value;
                lbl.Visible = true;
            }
        }

        public void RedirectToUploadPhotoPage()
        {
            // clear the uploaded photo list in session before redirect 
            ISessionService sessionService = IocContainer.GetInstance<ISessionService>();
            sessionService.ClearSessionVariable(SessionNames.ForSalePhotoList);

            Page.ClientScript.RegisterStartupScript(this.GetType(), "Redirect", "redirectToUploadPhotoPage();", true);
        }
    }
}
